package com.dylan.历史.基础;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Dylan on 2018/9/4.
 */
public class 泛型_上界与下界 {

    public static void main(String[] args) {
        List<Integer> source = new ArrayList<>();
        source.add(1);
        source.add(2);
        List<Number> target = new ArrayList<>();
        target.add(0);
        target.add(0);
        copy(source, target);
        System.out.println(target);
    }

    // 泛型结构只参与"读"操作则限定上界(extents关键字)
    private static <E> void read(List<? extends E> list, E item) {
        // list.add(item);
        for (E e : list) {
            System.out.println(e);
        }
    }

    // 泛型结构只参与"写"操作则限定下界(super关键字)
    private static <E> void write(List<? super E> list, E item) {
        list.add(item);
        // for (E e : list) {
        //     System.out.println(e);
        // }
    }

    // source用来读取，用extends限定上界；target用来写入，用super限定下界
    private static <T> void copy(List<? extends T> source, List<? super T> target) {
        for (int i = 0, j = 0; i < source.size(); i++, j++) {
            target.set(j, source.get(i));
        }
    }
}
